
package andre.grids.db;

import andre.grids.db.exceptions.DbDuplicatedEntry;
import andre.grids.db.dataclasses.*;
import com.db4o.*;
import com.db4o.query.Predicate;
import java.util.*;
import java.util.regex.*;

/**
 *
 * @author andre
 */
public class DbDirectoryQueries extends DbQueries<DbDirectory> {
    
    public DbDirectoryQueries()
    {
        super.setDb(Database.getGridFsDb());
    }
    
    public DbDirectory getDirByName(String name)
    {
        try
        {
            DbDirectory template= new DbDirectory();
            template.setDirName(name);
            
            Object value = super.getSingleObjectByPrototype(template, false);
            if (value == null)
                return null;
            return (DbDirectory)value;
        }
        catch(DbDuplicatedEntry e)
        {
            andre.grids.util.log.Log.logException(e, this);
        }
        return null;
    }
    
    public DbDirectory getDirByName(String name, int activationSize)
    {
        DbDirectory dir = getDirByName(name);
        if (dir != null)
            super.getDb().getObjects().activate(dir, activationSize);
        return dir;
    }
    
    public DbDirectory[] listAll() {        
        ObjectSet<DbDirectory> queryResult = super.getObjectListByPrototype(new DbDirectory());
        DbDirectory[] resultArray = new DbDirectory[queryResult.size()];
        int pos = 0;
        for(DbDirectory dir: queryResult) {            
            super.getDb().getObjects().activate(dir, 1);
            resultArray[pos++] = dir;
        }
        
       java.util.Arrays.sort(resultArray,new Comparator() {
            public int compare(Object arg0, Object arg1) {
                return ((DbDirectory)arg0).getDirName().compareTo(((DbDirectory)arg1).getDirName());
            }
        });
        
        return resultArray;        
    }
    
    public DbDirectory[] listAll(final String parent) {
        
        ObjectSet<DbDirectory> dirs = super.getDb().getObjects().query(new Predicate<DbDirectory>() {

            @Override
            public boolean match(DbDirectory arg0) {
                andre.grids.util.log.Log.debug("Analisando: " + arg0.getDirName() + " contra: " + parent);
                return arg0.getDirName().startsWith(parent);
            }
        });
        
        DbDirectory [] result = new DbDirectory[dirs.size()];
        Iterator<DbDirectory> it = dirs.iterator();
        int x = 0;
        for(;it.hasNext();)
            result[x++] = it.next();
        return result;
    }
    
}
